package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

@RestController
@RequestMapping("admin/product/")
public class FileUploadController {

    @Value("${fileServer.url}")
    private String fileServerUrl;

    //http://api.gmall.com/admin/product/fileUpload
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws IOException, MyException {
        String configfile = this.getClass().getResource("/tracker.conf").getFile();

        String path = null;
        if (configfile != null){
            ClientGlobal.init(configfile);

            TrackerClient trackerClient = new TrackerClient();

            TrackerServer connection = trackerClient.getConnection();

            StorageClient1 storageClient1 = new StorageClient1(connection,null);

            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            path = storageClient1.upload_appender_file1(file.getBytes(), extension, null);

        }

        return Result.ok(fileServerUrl+path);
    }
}
